<template>
  <div class="knowledge-manage">
    <!-- 知识库标题 -->
    <div class="knowledge-header">
      <h3>{{ selectedRole?.roleName }} 的知识库</h3>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加知识
      </el-button>
    </div>

    <!-- 搜索框 -->
    <div class="search-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索知识库内容..."
        @keyup.enter="handleSearch"
        clearable
        size="large"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
        <template #append>
          <el-button @click="handleSearch" type="primary">
            搜索
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 知识库列表 -->
    <div class="knowledge-list" v-if="knowledgeList.length > 0">
      <el-card v-for="doc in knowledgeList" :key="doc.id" class="knowledge-item">
        <div class="doc-header">
          <h4>{{ doc.title }}</h4>
          <div class="doc-actions">
            <el-tag :type="getStatusType(doc.status)" size="small">
              {{ getStatusText(doc.status) }}
            </el-tag>
            <el-button type="danger" size="small" @click="handleDelete(doc.id)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </div>
        <div class="doc-content">
          {{ doc.content?.substring(0, 200) }}...
        </div>
        <div class="doc-meta">
          <span class="meta-item">
            <el-icon><Document /></el-icon>
            类型: {{ doc.documentType }}
          </span>
          <span class="meta-item">
            <el-icon><Clock /></el-icon>
            创建时间: {{ formatTime(doc.createTime) }}
          </span>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="暂无知识库数据">
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          添加第一个知识
        </el-button>
      </el-empty>
    </div>

    <!-- 添加知识弹窗 -->
    <el-dialog 
      v-model="showAddDialog" 
      title="添加知识" 
      width="500px"
      class="add-knowledge-dialog"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="activeTab" class="knowledge-tabs">
        <!-- 文本知识 -->
        <el-tab-pane label="文本知识" name="text">
          <el-form :model="textForm" label-width="80px" class="text-form">
            <el-form-item label="标题" required>
              <el-input 
                v-model="textForm.title" 
                placeholder="请输入知识标题"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="内容" required>
              <el-input
                v-model="textForm.content"
                type="textarea"
                :rows="8"
                placeholder="请输入知识内容"
                maxlength="2000"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 文件上传 -->
        <el-tab-pane label="文件上传" name="file">
          <div class="upload-section">
            <el-upload
              ref="uploadRef"
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1"
              drag
              class="upload-dragger"
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 txt, pdf, doc, docx 等格式文件，大小不超过10MB
                </div>
              </template>
            </el-upload>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAdd" :loading="adding">
            <el-icon><Plus /></el-icon>
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, UploadFilled, Delete, Document, Clock } from '@element-plus/icons-vue'
import {
  addTextKnowledge,
  addFileKnowledge,
  getKnowledgeByRole,
  deleteKnowledge,
  searchKnowledge
} from '@/api/knowledge'

const props = defineProps({
  selectedRole: {
    type: Object,
    default: null
  }
})

// 响应式数据
const knowledgeList = ref([])
const searchQuery = ref('')
const showAddDialog = ref(false)
const activeTab = ref('text')
const adding = ref(false)
const uploadRef = ref()

// 表单数据
const textForm = reactive({
  title: '',
  content: ''
})
const selectedFile = ref(null)

// 获取知识库列表
const fetchKnowledgeList = async () => {
  if (!props.selectedRole?.id) return
  
  try {
    const res = await getKnowledgeByRole(props.selectedRole.id)
    if (res.code === 200) {
      knowledgeList.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取知识库列表失败')
  }
}

// 搜索知识库
const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    fetchKnowledgeList()
    return
  }
  
  try {
    const res = await searchKnowledge(props.selectedRole.id, searchQuery.value)
    if (res.code === 200) {
      // 这里可以显示搜索结果
      console.log('搜索结果:', res.data)
    }
  } catch (error) {
    ElMessage.error('搜索失败')
  }
}

// 文件选择
const handleFileChange = (file) => {
  console.log('文件选择:', file)
  selectedFile.value = file.raw
  console.log('文件选择:', selectedFile.value)
}

// 添加知识
const handleAdd = async () => {
  if (activeTab.value === 'text') {
    if (!textForm.title.trim()) {
      ElMessage.warning('请输入知识标题')
      return
    }
    if (!textForm.content.trim()) {
      ElMessage.warning('请输入知识内容')
      return
    }
  } else {
    if (!selectedFile.value) {
      ElMessage.warning('请选择文件')
      return
    }
  }

  adding.value = true
  
  try {
    if (activeTab.value === 'text') {
      // 添加文本知识
      await addTextKnowledge({
        roleId: props.selectedRole.id,
        title: textForm.title,
        content: textForm.content
      })
      
      // 重置表单
      textForm.title = ''
      textForm.content = ''
    } else {
      // 上传文件知识
      console.log('上传文件:', selectedFile.value)
      const res = await addFileKnowledge(props.selectedRole.id, selectedFile.value)
      if (res.code !== 200) {
        throw new Error(res.msg || '上传失败')
      }
      
      selectedFile.value = null
      uploadRef.value?.clearFiles()
    }
    
    ElMessage.success('添加成功')
    showAddDialog.value = false
    fetchKnowledgeList()
  } catch (error) {
    console.error('添加失败:', error)
    ElMessage.error(error.message || '添加失败')
  } finally {
    adding.value = false
  }
}

// 删除知识
const handleDelete = async (documentId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个知识文档吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteKnowledge(documentId, props.selectedRole.id)
    ElMessage.success('删除成功')
    fetchKnowledgeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 工具函数
const getStatusType = (status) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'warning'
    case -1: return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1: return '已处理'
    case 0: return '处理中'
    case -1: return '处理失败'
    default: return '未知'
  }
}

const formatTime = (time) => {
  return new Date(time).toLocaleString()
}

// 监听角色变化
watch(() => props.selectedRole, fetchKnowledgeList, { immediate: true })
</script>

<style scoped>
.knowledge-manage {
  display: flex;
  flex-direction: column;
  gap: 24px;
  height: 100%;
}

/* 知识库头部样式 */
.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-fill-color-extra-light) 100%);
  border-radius: 12px;
  border: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.knowledge-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;
  gap: 8px;
}

.knowledge-header h3::before {
  content: '📚';
  font-size: 20px;
}

/* 搜索区域样式 */
.search-section {
  margin: 0;
}

.search-section .el-input {
  border-radius: 8px;
}

/* 知识库列表样式 */
.knowledge-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 450px;
  overflow-y: auto;
  padding-right: 8px;
}

.knowledge-item {
  border-radius: 12px;
  border: 1px solid var(--el-border-color-lighter);
  transition: all 0.3s ease;
  overflow: hidden;
}

.knowledge-item:hover {
  border-color: var(--el-color-primary-light-7);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

:deep(.knowledge-item .el-card__body) {
  padding: 24px;
}

/* 文档头部样式 */
.doc-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 16px;
}

.doc-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  flex: 1;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.doc-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

/* 文档内容样式 */
.doc-content {
  margin: 0 0 20px 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
  line-height: 1.6;
  background: var(--el-fill-color-extra-light);
  padding: 16px 20px;
  border-radius: 8px;
  border-left: 4px solid var(--el-color-primary-light-7);
  position: relative;
}

.doc-content::before {
  content: '"';
  position: absolute;
  top: 8px;
  left: 8px;
  font-size: 24px;
  color: var(--el-color-primary-light-5);
  font-family: serif;
}

/* 文档元信息样式 */
.doc-meta {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  padding: 6px 12px;
  background: var(--el-fill-color-light);
  border-radius: 6px;
  flex: 1;
  justify-content: center;
}

.meta-item .el-icon {
  font-size: 14px;
  color: var(--el-color-primary);
}

/* 空状态样式 */
.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  background: var(--el-fill-color-extra-light);
  border-radius: 12px;
  border: 2px dashed var(--el-border-color-lighter);
}

/* 知识库列表滚动条样式 */
.knowledge-list::-webkit-scrollbar {
  width: 6px;
}

.knowledge-list::-webkit-scrollbar-track {
  background: var(--el-fill-color-lighter);
  border-radius: 3px;
}

.knowledge-list::-webkit-scrollbar-thumb {
  background: var(--el-border-color-darker);
  border-radius: 3px;
}

.knowledge-list::-webkit-scrollbar-thumb:hover {
  background: var(--el-border-color-dark);
}

/* 添加知识弹窗样式 */
.add-knowledge-dialog {
  border-radius: 12px;
}

:deep(.add-knowledge-dialog .el-dialog) {
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
}

:deep(.add-knowledge-dialog .el-dialog__header) {
  padding: 24px 24px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-fill-color-extra-light) 100%);
}

:deep(.add-knowledge-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

:deep(.add-knowledge-dialog .el-dialog__body) {
  padding: 24px;
}

/* 标签页样式 */
.knowledge-tabs {
  margin-top: 0;
}

:deep(.knowledge-tabs .el-tabs__header) {
  margin-bottom: 24px;
}

:deep(.knowledge-tabs .el-tabs__content) {
  padding-top: 0;
}

/* 文本表单样式 */
.text-form {
  margin-top: 16px;
}

:deep(.text-form .el-form-item) {
  margin-bottom: 24px;
}

:deep(.text-form .el-form-item__label) {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

/* 上传区域样式 */
.upload-section {
  margin-top: 16px;
}

.upload-dragger {
  width: 100%;
}

:deep(.upload-dragger .el-upload-dragger) {
  border-radius: 12px;
  border: 2px dashed var(--el-border-color-lighter);
  transition: all 0.3s ease;
  padding: 40px 20px;
}

:deep(.upload-dragger .el-upload-dragger:hover) {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

:deep(.upload-dragger .el-icon--upload) {
  font-size: 48px;
  color: var(--el-color-primary-light-5);
  margin-bottom: 16px;
}

:deep(.upload-dragger .el-upload__text) {
  font-size: 16px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
}

:deep(.upload-dragger .el-upload__tip) {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 8px;
}

/* 弹窗底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .knowledge-manage {
    gap: 16px;
  }
  
  .knowledge-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 16px 20px;
  }
  
  .knowledge-header h3 {
    text-align: center;
  }
  
  .doc-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .doc-actions {
    justify-content: flex-end;
  }
  
  .doc-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .meta-item {
    justify-content: flex-start;
  }
  
  :deep(.knowledge-item .el-card__body) {
    padding: 20px;
  }
}

@media (max-width: 480px) {
  .knowledge-list {
    max-height: 350px;
  }
  
  :deep(.add-knowledge-dialog .el-dialog) {
    width: 95% !important;
    margin: 0 2.5%;
  }
  
  :deep(.add-knowledge-dialog .el-dialog__body) {
    padding: 16px;
  }
}
</style>